package com.example.blogsystem.utils;

import com.example.blogsystem.model.Blog;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.time.LocalDate;
import java.util.Scanner;
import java.util.UUID;

@Slf4j
public class BlogStoreUtils {
    //获取对应的目录
    private static String getDir(){
        LocalDate localDate = LocalDate.now();
        return "./resources/" + localDate;
    }

    private static String getPath(String blogName){
        return getDir() + "/" + blogName + ".txt";
    }

    private static boolean checkBlogFileExists(String filePath){
        File file = new File(filePath);
        return file.exists();
    }

    private static void createFiles(String blogName) throws IOException {
        //1、创建对应的目录
        File directory = new File(getDir());
        if(!directory.exists()){
            boolean success = directory.mkdirs();
            if(!success){
                throw new IOException("[BlogStoreUtils] 创建目录失败" + directory.getAbsolutePath());
            }
        }
        //2、创建对应的文件
        File blogFile = new File(getPath(blogName));
        if(!blogFile.exists()){
            boolean success = blogFile.createNewFile();
            if(!success){
                throw new IOException("[BlogStoreUtils] 创建文件失败：" + blogFile.getAbsolutePath());
            }
        }
    }

    public static String writeBlog(Blog blog) throws IOException {
        //创建文件
        String blogName = UUID.randomUUID() + "_" + blog.getTitle();
        createFiles(blogName);
        //写文件
        try(OutputStream outputStream = new FileOutputStream(getPath(blogName));
            PrintWriter printWriter = new PrintWriter(outputStream)){
            printWriter.println(blog.getContent());
            printWriter.flush();
            return getDir() + "/" + blogName + ".txt";
        } catch (IOException e){
            e.printStackTrace();
        }
        return "";
    }

    public static void readBlog(Blog blog) throws IOException {
        //判断文件是否存在
        //log.info("[readBlog] content:{}", blog.getContent());
        if(!checkBlogFileExists(blog.getContent())){
            throw new IOException("[BlogStoreUtils] 文件不存在：" + blog.getContent());
        }
        //读取文件
        String filePath = blog.getContent();
        StringBuilder content = new StringBuilder();
        //此处使用字节流，是为了保证读取文件中的换行符
        try(InputStream inputStream = new FileInputStream(new File(filePath))){

            byte[] inputByte = new byte[inputStream.available()];

            while(inputStream.read(inputByte) != -1){
                String tmp = new String(inputByte, 0, inputByte.length);
                content.append(tmp);
            }

            blog.setContent(content.toString());
        } catch (IOException e){
            e.printStackTrace();
        }
    }
}
